﻿#region License


// Virtual Essentials - http://www.Virtual-Essentials.com
// Copyright (c) 2005-2013
// 
//  This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

//using DotNetNuke;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Framework;
using DotNetNuke.Web.Client.ClientResourceManagement;
using DotNetNuke.Common.Utilities;

using VirtualEssentials.DNN.Modules.Testimonials.Controller;
using System.Web.UI.WebControls;

namespace VirtualEssentials.DNN.Modules.Testimonials
{
    /// <summary>
    /// Summary description for Testimonial
    /// </summary>
    public partial class Testimonial : DotNetNuke.Entities.Modules.PortalModuleBase, DotNetNuke.Entities.Modules.IActionable
    {
        DataProvider data = new DataProvider();
       
        // public readonly ModuleActionCollection ModuleActions { get; }
        string AddUrl = string.Empty;
        string ContainerClass,AnimationOption;
        string orientation = string.Empty;
        string AddNewLinkClass = string.Empty;
        string AddNewLinkText = string.Empty;
        string NumberToDisplay = string.Empty;
        string AddNewPlacement = string.Empty;
        string OrderBy = string.Empty;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
            ServicesFramework.Instance.RequestAjaxScriptSupport();
            ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
            //create a reference to the module security to determine custom module user permissions
            ModuleSecurity ms = new ModuleSecurity(this.ModuleConfiguration);
            //build the redirect to the pop up page to add new testimonials
            AddUrl = DotNetNuke.Common.Globals.NavigateURL(this.TabId, "AddTestimonial", "mid=" + this.ModuleId.ToString());
            //check for settings
            if (string.IsNullOrEmpty((string)Settings["ContainerClass"]))
            {
                ContainerClass = "veTestimonialRotator";
            }
            else
            {
                ContainerClass = (string)Settings["ContainerClass"];
            }

             if (string.IsNullOrEmpty((string)Settings["AnimationOption"]))
            {
                AnimationOption = "vetestimonials.js"; //default to horizontal
            }
            else
            {
                AnimationOption = (string)Settings["AnimationOption"];
            }

            if (string.IsNullOrEmpty((string)Settings["OrderBy"]))
            {
                OrderBy = "TestimonialDateDesc"; //default to newest first
            }
            else
            {
                OrderBy = (string)Settings["OrderBy"];
            }

            if (AnimationOption.Contains("simpleScroll"))
            {
                if (AnimationOption.Substring(AnimationOption.Length - 1, 1) == "h")
                {
                    orientation = "horizontal";
                }
                else
                {
                    orientation = "vertical";
                }
                AnimationOption = AnimationOption.Substring(0, AnimationOption.Length - 1);
            }
        
                //determine which script to load, if any
              switch (AnimationOption) {
                  case "vetestimonials.js":
                        Page.ClientScript.RegisterClientScriptResource(typeof(Testimonials.Testimonial), "VirtualEssentials.DNN.Modules.Testimonials.js.vetestimonials.js");
                    break;
                  case "simpleScroll.js":
                    Page.ClientScript.RegisterClientScriptResource(typeof(Testimonials.Testimonial), "VirtualEssentials.DNN.Modules.Testimonials.js.simpleScroll.js");
                    break;
                  case "none":
                    break;
            }


              if (string.IsNullOrEmpty((string)Settings["AddNewLinkClass"]))
              {
                  AddNewLinkClass = "veTestimonialAddNewLink"; //default to horizontal
              }
              else
              {
                  AddNewLinkClass = (string)Settings["AddNewLinkClass"];
              }


              if (string.IsNullOrEmpty((string)Settings["AddNewLinkText"]))
              {
                  AddNewLinkText = "Add a Testimonial"; 
              }
              else
              {
                  AddNewLinkText = (string)Settings["AddNewLinkText"];
              }

              if (string.IsNullOrEmpty((string)Settings["NumberToDisplay"]))
              {
                  NumberToDisplay = "10"; //default to 10
              }
              else
              {
                  NumberToDisplay = (string)Settings["NumberToDisplay"];
              }

              if (string.IsNullOrEmpty((string)Settings["AddNewPlacement"]))
              {
                  AddNewPlacement = "Top"; 
              }
              else
              {
                  AddNewPlacement = (string)Settings["AddNewPlacement"];
              }

            //add controls to hold the module and tab id, required for the 
            //ActiveModule support needed on the WebAPI controller
            HtmlGenericControl veModuleId = new HtmlGenericControl();
            veModuleId.Attributes.Add("class", "veModuleId");
            veModuleId.Attributes.Add("style", "display:none;");
            Page.Controls.Add(veModuleId);
            veModuleId.InnerText = this.ModuleId.ToString();

            HtmlGenericControl veTabID = new HtmlGenericControl();
            veTabID.Attributes.Add("class", "veTabID");
            veTabID.Attributes.Add("style", "display:none;");
            Page.Controls.Add(veTabID);
            veTabID.InnerText = this.TabId.ToString();
                

            System.Web.UI.WebControls.Label lblTestimonies = new System.Web.UI.WebControls.Label();
            lblTestimonies.ID = "lblTestimonies_" + ModuleId;
            lblTestimonies.Visible = ms.HasViewTestimonialPermission;

            //TestimonialController objController = new TestimonialController();
           List<TestimonialInfo> colTestimonies = new List<TestimonialInfo>();
           colTestimonies = (List<TestimonialInfo>)data.GetPublishedTestimonials(ModuleId, OrderBy, Convert.ToInt32(NumberToDisplay));

            //get the template for the module from the settings
            string template = (string)Settings["DisplayTemplate"];
            string thisTemplate = template; //new template with replacements



            //replace the user defined template with the knockout structure
            StringBuilder templatedData = new StringBuilder();

            if (AddNewPlacement == "Top" | AddNewPlacement == "Both" )
            {
                //hide the add new testimonial if the user doesn't have proper permission
                if (ms.HasAddTestimonialPermission)
                {
                    //build the add new button stub
                    System.Web.UI.WebControls.HyperLink btnAddTop = new System.Web.UI.WebControls.HyperLink();
                    btnAddTop.ID = "btnAdd_Top" + ModuleId;
                    btnAddTop.CssClass = AddNewLinkClass;
                    btnAddTop.Text = AddNewLinkText;

                    //if website has PopUp Enabled
                    if (PortalSettings.EnablePopUps)
                    {
                        btnAddTop.Attributes.Add("onclick", "return " + DotNetNuke.Common.Utilities.UrlUtils.PopUpUrl(AddUrl, this, PortalSettings, true, false));
                    }
                    else
                    {
                        btnAddTop.NavigateUrl = DotNetNuke.Common.Globals.NavigateURL(this.TabId, "AddTestimonial", "mid=" + this.ModuleId.ToString());
                    }
                    this.Controls.Add(btnAddTop);
                }
            }

            templatedData.Append("<div id=\"veTestimonial_" + ModuleId + "\" class=\"" + ContainerClass + "\" data-bind=\"foreach: testimonials\">");

            foreach (TestimonialInfo item in colTestimonies)
            {
                 templatedData.Append(BuildTemplate(thisTemplate, item));
            }

            ////close the container tag
            templatedData.Append("</div>");
            //return the template
            lblTestimonies.Text = templatedData.ToString();

            this.Controls.Add(lblTestimonies);
            if (AddNewPlacement == "Bottom" | AddNewPlacement == "Both")
            {
                //hide the add new testimonial if the user doesn't have proper permission
                if (ms.HasAddTestimonialPermission)
                {
                    //build the add new button stub
                    System.Web.UI.WebControls.HyperLink btnAddBottom = new System.Web.UI.WebControls.HyperLink();
                    btnAddBottom.ID = "btnAdd_Bottom" + ModuleId;
                    btnAddBottom.CssClass = AddNewLinkClass;
                    btnAddBottom.Text = AddNewLinkText;
                    if (PortalSettings.EnablePopUps)
                    {
                        btnAddBottom.Attributes.Add("onclick", "return " + DotNetNuke.Common.Utilities.UrlUtils.PopUpUrl(AddUrl, this, PortalSettings, true, false));
                    }
                    else
                    {
                        btnAddBottom.NavigateUrl=DotNetNuke.Common.Globals.NavigateURL(this.TabId, "AddTestimonial", "mid=" + this.ModuleId.ToString()); 
                    }
                    this.Controls.Add(btnAddBottom);
                }
            }


            //build script block
            StringBuilder jQueryDocReadyScript = new StringBuilder();
                //start the jquery doc ready script
            jQueryDocReadyScript.AppendLine("$(document).ready(function() {");

                //add rotator code
                string jQuerySelector = "#veTestimonial_" + ModuleId;
            
                 //determine which script to load, if any
                switch (AnimationOption)
                {
                    case "vetestimonials.js":
                        jQueryDocReadyScript.AppendLine("$('" + jQuerySelector + "').randomize('div').rotaterator({fadeSpeed: 1200, pauseSpeed: 6000});");
                        break;

                    case "simpleScroll.js":
                        jQueryDocReadyScript.AppendLine("$('" + jQuerySelector + "').simplyScroll({orientation: '" + orientation + "', pauseOnHover:true , customClass: '" + ContainerClass + "'});");
                        break;
                    case "none":
                        break;
                }


    //close the jQuery doc ready script
            jQueryDocReadyScript.AppendLine("});");
            //register to page
            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "jQueryDocReadyScriptVE_" + ModuleId, jQueryDocReadyScript.ToString(), true);

            }
            catch (Exception exc)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
            }

        }   
                
        /// <summary>
        /// Build the template for layout for an individual item
        /// </summary>
        /// <returns></returns>
        protected string BuildTemplate(string Template, TestimonialInfo item)
        {
            try {

            Template = "<div class=\"TestimonialItem\"><span id=\"" + item.TestimonialID + "\"></span>" + Template;
            Template = Template.Replace("[Testimonial]", String.Format("{0} ", item.Testimonial));
            Template = Template.Replace("[FirstName]", String.Format("{0} ", item.AuthorFirstName));
            Template = Template.Replace("[LastName]", String.Format("{0} ", item.AuthorLastName));
            Template = Template.Replace("[FirstNameInitial]", String.Format("{0} ", item.AuthorFirstName.Substring(0, 1)));
            Template = Template.Replace("[LastNameInitial]", String.Format("{0} ", item.AuthorLastName.Substring(0, 1)));
            Template = Template.Replace("[Date]", String.Format("{0} ", item.TestimonialDate));
            Template = Template.Replace("[Location]", String.Format("{0} ", item.AuthorLocation));
            Template = Template.Replace("[Title]", String.Format("{0} ", item.AuthorTitle));
            Template = Template.Replace("[Website]", String.Format("{0} ", item.AuthorWebsite));
            Template = Template + "</div>";
              }
            catch (Exception exc)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
            }

            return Template;
        }
                
        #region optionals
        public ModuleActionCollection ModuleActions
        {
            get
            {
                //add the Manage Testimonials action button
                var Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(),
                    "Manage Testimonials",
                    ModuleActionType.EditContent,
                    "",
                    "",
                    EditUrl(),
                    false,
                    DotNetNuke.Security.SecurityAccessLevel.Edit,
                    true,
                    false);

                Actions.Add(GetNextActionID(),
                   "Add New Testimonial",
                   ModuleActionType.EditContent,
                   "",
                   "",
                   DotNetNuke.Common.Globals.NavigateURL(this.TabId, "AddTestimonial", "mid=" + this.ModuleId.ToString()),
                   false, 
                   DotNetNuke.Security.SecurityAccessLevel.Edit,
                   true,
                   false);

                return Actions;
            }
        }


       



        #endregion



    }
}